//
//  NSObject+ModelJson.m
//  ModelJsonDemo
//
//  Created by苏沫离 on 2018/3/21.
//  Copyright © 2018年 longlong. All rights reserved.
//

#import "NSObject+ModelJson.h"
#import <objc/runtime.h>

@implementation NSObject (ModelJson)

+ (instancetype)modelWithParserDict:(NSDictionary *)dict
{
    id objc = [[self alloc] init];
    unsigned int count = 0;
    Ivar *ivarList = class_copyIvarList(self, &count);
    for (int i = 0; i < count; i ++)
    {
        Ivar ivar = ivarList[i];
        NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        key = [key substringFromIndex:1];
        id value = dict[key];
        
        
        NSString *varType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
        varType = [varType stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        varType = [varType stringByReplacingOccurrencesOfString:@"@" withString:@""];
        
        if ([value isKindOfClass:[NSDictionary class]] &&
            [varType hasPrefix:@"NS"] == NO)
        {
            Class dictModel = NSClassFromString(varType);
            value = [dictModel modelWithParserDict:value];
        }
        
        
        if ([value isKindOfClass:[NSArray class]])
        {
            if ([self respondsToSelector:@selector(arrayContainModelClass)])
            {
                id idSelf = self;
                NSString *arrayType = [idSelf arrayContainModelClass][key];
                Class arrayClass = NSClassFromString(arrayType);
                
                NSMutableArray *reArray = [NSMutableArray array];
                for (NSDictionary *dictionary in value)
                {
                    [reArray addObject:[arrayClass modelWithParserDict:dictionary]];
                }
                value = reArray;
            }
        }
        
        if (value)
        {
            [objc setValue:value forKey:key];
        }
    }
    free(ivarList);
    return objc;
}

@end
